package com.house.keeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.house.keeper.base.Result;
import com.house.keeper.base.ResultCode;
import com.house.keeper.entity.Car;
import com.house.keeper.entity.bean.CommunityCar;
import com.house.keeper.entity.vo.CarVo;
import com.house.keeper.mapper.CarMapper;
import com.house.keeper.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zjj
 * @date 2022-06-01 08:42:43
 *
 * @description 
 */
@Service
public class CarServiceImpl implements CarService {
    @Autowired
    private CarMapper carMapper;

    /**
     * 分页查询
     *
     * @param carVo 查询条件
     * @return
     */
    @Override
    public Result selectByPage(CarVo carVo) {
        PageHelper.startPage(carVo.getPage(),carVo.getLimit());

        QueryWrapper<Car> wrapper = new QueryWrapper<>();


        List<Car> carList = carMapper.selectList(wrapper);

        PageInfo<Car> pageInfo = new PageInfo<>(carList);
        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return
     */
    @Override
    public Result delete(Integer id) {
        int row = carMapper.deleteById(id);
        if(row<=0){
            return Result.failure(ResultCode.PARAM_IS_INVALID);
        }
        return Result.success();
    }

    /**
     * 添加或修改
     *
     *  回滚：一般抛出的是RuntimeExcept异常
     *  在spring框架下，所有的异常都被org.springframework重写为RuntimeExcept
     * @param car
     * @return
     */
    @Override
    @Transactional
    public Result update(Car car) {
        if(car.getId()!=null){

            int row=carMapper.updateById(car);
            if(row<=0){
                return Result.failure(ResultCode.PARAM_IS_INVALID);
            }
        }else{
//            添加
            int row =carMapper.insert(car);
            if(row<=0){
                return Result.failure(ResultCode.PARAM_IS_INVALID);
            }
        }
        return Result.success();
    }

    /**
     * 查询小区地库租用的车辆总数
     *
     * @return
     */
    @Override
    public Result getCarNum() {
        List<CommunityCar> communityCars=carMapper.selectCarSum();
        return Result.success(communityCars);
    }

}

